import requests
import json
import datetime
import re

def get_brent_oil_data():
    # Get current date
    current_date = datetime.datetime.now()
    date_str = f"{current_date.year}_{current_date.month}_{current_date.day}"
    
    # API URL
    url = f"https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_OIL{date_str}=/GlobalFuturesService.getGlobalFuturesDailyKLine?symbol=OIL&_={date_str}&source=web"
    
    try:
        response = requests.get(url)
        if response.status_code == 200:
            # Extract the JSON data from the JSONP response
            content = response.text
            # Use regex to extract the JSON array
            json_match = re.search(r'_OIL\d+_\d+_\d+=\((.*)\);', content)
            if json_match:
                json_data = json.loads(json_match.group(1))
                return json_data
            else:
                print("Failed to parse JSONP response")
                return None
        else:
            print(f"Failed to fetch data: HTTP {response.status_code}")
            return None
    except Exception as e:
        print(f"Error fetching data: {e}")
        return None

def format_as_markdown_table(data, num_rows=20):
    """Format the data as a Markdown table with the most recent entries."""
    if not data:
        return "No data available"
    
    # Get the most recent entries
    recent_data = data[-num_rows:]
    
    # Create table header
    table = "| 日期 | 开盘价 | 最高价 | 最低价 | 收盘价 | 成交量 |\n"
    table += "| ---- | ------ | ------ | ------ | ------ | ------ |\n"
    
    # Add rows in reverse order (most recent first)
    for item in reversed(recent_data):
        date = item['date']
        open_price = item['open']
        high = item['high']
        low = item['low']
        close = item['close']
        volume = item['volume']
        
        table += f"| {date} | {open_price} | {high} | {low} | {close} | {volume} |\n"
    
    return table

def filter_last_2_years(data):
    """Filter data to include only the last 2 years"""
    if not data:
        return []
    
    # Calculate the date 2 years ago
    today = datetime.datetime.now()
    two_years_ago = today - datetime.timedelta(days=365*2)
    two_years_ago_str = two_years_ago.strftime("%Y-%m-%d")
    
    # Filter the data to include only entries from the last 2 years
    filtered_data = [item for item in data if item['date'] >= two_years_ago_str]
    
    return filtered_data

def main():
    data = get_brent_oil_data()
    if data:
        # Filter to get the last 2 years of data
        last_2_years_data = filter_last_2_years(data)
        
        # Display the last 2 years data
        print(f"## 布伦特原油最近2年数据 (共{len(last_2_years_data)}条记录)")
        markdown_table = format_as_markdown_table(last_2_years_data, len(last_2_years_data))
        print(markdown_table)
        
    else:
        print("Failed to retrieve Brent oil data")

if __name__ == "__main__":
    main()